package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.Result;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.service.YddCateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/ydd_cate")
public class YddCateController {

    @Autowired
    private YddCateService yddCateService;

    /**
     * 分类列表
     */
    @GetMapping("/list")
    public Result categoryList(String catename, Long page, Long limit) {
        //构造分页对象
        Page<YddCate> pageInfo = new Page<>(page, limit);

        //分页条件查询条件
        LambdaQueryWrapper<YddCate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(catename != null, YddCate::getCatename, catename);
        queryWrapper.orderByAsc(YddCate::getSort_num);
        Page<YddCate> pageCate = yddCateService.page(pageInfo, queryWrapper);
        PageResult answer = PageResult.answer(pageCate.getTotal(), limit, pageCate.getCurrent(), pageCate.getRecords());

        return Result.ok("OK", answer);

    }

    //分类列表_全部
    @GetMapping("/all")
    public Result all() {

        List<YddCate> list = yddCateService.list();
        return Result.ok("", list);
    }

    //分类添加
    @PostMapping("/add")
    public Result add(@RequestBody YddCate yddCate) {
        yddCateService.save(yddCate);
        return Result.ok("新增成功", null);
    }

    /*
       修改数据
    */
    @PostMapping("/update")
    public Result update(@RequestBody YddCate yddCate){
        yddCateService.updateById(yddCate);
        return Result.ok("修改成功",null);
    }

    /*
       回显数据
    */
    @GetMapping("/rowInfo")
    public Result rowInfo(Integer id){
        YddCate byId = yddCateService.getById(id);
        if(byId != null){
            return Result.ok("",byId);
        }
        return Result.error("没有数据");
    }

    /*
       删除分类
    */
    @GetMapping("/del")
    public Result del(Integer id){
        yddCateService.removeById(id);
        return Result.ok("删除成功",null);
    }
}
